{% extends "themes/" + sysSettings.systemTheme + "/layout.html" %}

{% block head %}
<title>{{sysSettings.siteName}} - {{channel.channelName}}</title>
<meta name="twitter:card" content="player" />
<meta property="og:site_name" content="{{sysSettings.siteName}}" />
<meta property="og:title" content="{{channel.channelName}}" />
<meta property="og:type" content="video.other" />
<meta property="og:url" content="{{request.url|normalize_url}}" />
<meta property="og:image" content="{{request.url_root|normalize_urlroot}}/images/{{channel.imageLocation}}" />
<meta property="og:description" content="{{channel.description}}" />
<meta property="og:video" content="{{request.url_root|normalize_urlroot}}{{streamURL}}" />
<meta property="og:video:type" content="application/x-mpegURL" />

<script type="text/javascript" src="/static/vendor/socketio/js/socket.io.js"></script>
<script type="text/javascript" src="/static/vendor/popper/js/popper.min.js"></script>
<link href="/static/vendor/videojs/css/video-js.css" rel="stylesheet">
<script src="/static/vendor/videojs/js/video.js"></script>
<script src="/static/vendor/videojs-contrib-quality-levels/js/videojs-contrib-quality-levels.js"></script>
<link href="/static/vendor/videojs-http-source-selector/videojs-http-source-selector.css" rel="stylesheet">
<script src="/static/vendor/videojs-http-source-selector/videojs-http-source-selector.js"></script>

<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Expires" CONTENT="-1">

{% endblock %}

{% block body %}
<div class="container-fluid">
    <div class="row">
        <div class="col-lg col-xs-12 col-sm-12">
            <div class="index-video-title ml-2 my-2">
                <a href="/channel/{{channel.id}}"><span class="float-left"
                        id="channelName">{{channel.channelName}}</span></a>
                <h6 style="display: inline; margin: 0px;"><span id="liveIndicatorBadge"
                        class="float-left m-2 liveindicator badge badge-secondary"><b><i
                                class="fas fa-video-slash"></i><span class="d-none d-sm-none d-md-inline">
                                Offline</span></b></span> {% if channel.protected and sysSettings.protectionEnabled %}<span
                        class="liveindicator badge badge-info float-left m-2"><i class="fas fa-user-lock"></i><span
                            class="d-none d-sm-none d-md-inline"> Protected</span></span></h6>{% endif %}
            </div>
        </div>
        <div class="col-lg-auto col-sm-12" style="width:450px;">
            <ul id="channelPlayerMenu" class="nav nav-tabs">
                <li class="nav-item">
                    <a class="nav-link active" id="channel-tab" data-toggle="tab" href="#livechannel" role="tab"
                        aria-controls="home" aria-selected="true">Live Channel</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" id="videos-tab" data-toggle="tab" href="#videoList" role="tab"
                        aria-controls="profile" aria-selected="false">Videos</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" id="clips-tab" data-toggle="tab" href="#clipList" role="tab"
                        aria-controls="profile" aria-selected="false">Clips</a>
                </li>
            </ul>
        </div>
    </div>
    <div class="tab-content" id="tabList">
        <div class="tab-pane fade show active" id="livechannel" role="tabpanel" aria-labelledby="channel-tab">
            <div class="row">
                <div class="{% if channel.chatEnabled == True %}col-lg{% else %} col-12{% endif %} col-xs-12 col-sm-12"
                    id="videoWindow">
                    <div class="videoPanel">
                        <div class="player ml-2">
                            <div id="videoContainer">
                                <video id="video" class="shadow videoStream video-js vjs-big-play-centered"
                                    poster="/stream-thumb/{{channel.channelLoc}}.png" autoplay controls preload="auto"
                                    data-setup='{"fluid": true, "liveui": true}'>
                                    <p class="vjs-no-js">
                                        To view this video please enable JavaScript, and consider upgrading to a web
                                        browser that
                                        <a href="https://videojs.com/html5-video-support/" target="_blank">supports
                                            HTML5 video</a>
                                    </p>
                                </video>
                            </div>
                            <div id="offlineImage" style="display:none;">
                                <img class="videoStream shadow" {% if channel.offlineImageLocation != None %}
                                    src="/images/{{channel.offlineImageLocation}}" {% else %}
                                    src="/static/img/video-placeholder.jpg" {% endif %} onerror="this.onerror=null;this.src='/static/img/video-placeholder.jpg';">
                            </div>
                        </div>
                        <div class="row m-2">
                            <div class="video-buttons-row">
                                {% if channel.owningUser == current_user.id %}
                                <span class="float-left" style="margin-right: 10px">
                                    <button type="button" class="btn btn-primary ml-1" data-toggle="modal"
                                        data-target="#editModal">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                </span>
                                {% endif %}
                                <span class="float-left">
                                    <span id="streamMetadataName" class="stream-title"><b><i
                                                class="fas fa-video mr-2"></i>{% if stream != None %}
                                            {{stream.streamName|limit_title}} {% else %} No Stream
                                            {% endif %}</b></span><br />
                                    <span id="streamMetadataTopic"><b><i class="fas fa-hashtag mr-2"></i></b> <a
                                            href="/topic/{{stream.topic}}/">{% if stream != None %}
                                            {{stream.topic|get_topicName}} {% else %} {{channel.topic|get_topicName}}
                                            {% endif %}</a></span>
                                </span>
                                <span class="float-right">
                                        <i class="fas fa-users mx-2"></i> {{channel.views}}
                                        <i class="fas fa-star mx-2"></i> {{channel.subscriptions|length}}<br />
                                        <i class="fas fa-eye mx-2"></i> <span
                                            id="currentViewers">{{channel.currentViewers}}</span>
                                </span>
                                <span class="float-right">
                                    <div class="btn-group" role="group">
                                        <button id="btnGroupDrop1" type="button"
                                            class="btn btn-primary ml-1 dropdown-toggle" data-toggle="dropdown"
                                            aria-haspopup="true" aria-expanded="false"><i id="cog"
                                                class="fas fa-bars"></i></button>
                                        <div class="dropdown-menu" aria-labelledby="btnGroupDrop1">
                                            <a class="dropdown-item" data-toggle="modal" data-target="#shareModal"
                                                aria-pressed="false" autocomplete="off" href="#"><i
                                                    class="fas fa-share-alt"></i> Share stream</a>
                                            <a class="dropdown-item {% if channel.chatEnabled == False %}disabled{% endif %}"
                                                data-toggle="button" aria-pressed="false" autocomplete="off"
                                                onclick="toggleChat()" href="#"><i class="fas fa-eye-slash"></i> Toggle
                                                chat</a>
                                            <a class="dropdown-item" id="userList" tabindex="10" data-html="true"
                                                data-toggle="popover" title="User List" data-trigger="focus"
                                                data-content="" data-placement="top" href="#"><i
                                                    class="fas fa-users"></i> User list</a>
                                            <a class="dropdown-item" onClick="popoutChat();return false;"
                                                class="btn btn-primary {% if channel.chatEnabled == False %}disabled {% endif %}"
                                                title="Pop-out Chat" href="#"><i class="fas fa-comment"></i> Pop-out
                                                chat</a>
                                        </div>
                                    </div>
                                    <span class="float-right mx-1">
                                        {% if current_user.is_authenticated %}
                                        <button id="chanSubStateButton"
                                            class="btn {% if subState == True %} btn-outline-success {% else %} btn-outline-secondary {% endif %}"
                                            onclick='toggleChannelSub("{{channel.id}}")'>{% if subState == True %}<i
                                                class="fas fa-star"></i>{% else %}<i
                                                class="far fa-star"></i>{% endif %}</button>
                                        {% else %}
                                        <button id="chanSubStateButton" class="btn btn-outline-secondary disabled"
                                            disabled><i class="far fa-star"></i></button>
                                        {% endif %}
                                    </span>
                                    <button id="upvoteButton" type="button" class="btn btn-outline-secondary ml-1"
                                        onclick="changeUpvote();" title="Upvote"
                                        {% if current_user.is_authenticated==false %} disabled aria-disabled="true"
                                        {% endif %}>
                                        <i id="upVoteIcon" class="far fa-thumbs-up"> <span id="totalUpvotes"></span></i>
                                    </button>
                                </span>
                            </div>
                        </div>
                        <div class="row m-2">
                            <div class="channeldescription">{% if channel.description != None %}<p>
                                    {{channel.description|markdown}}</p> {% else %}No Description Available {% endif %}
                            </div>
                        </div>
                    </div>
                </div>
                {% if channel.chatEnabled == True %}
                <div id="chatside" class="col-lg-auto col-xs-12 col-sm-12">
                    <div class="row ml-2 mr-1">
                        <div class="index-video-title mb-2"><b>Chat</b></div>
                        <div class="chatbox" id="chatBlock">
                            <div id="chat" class="chat"></div><br>
                            <input id="text" class="form-control shadow" {% if current_user.is_authenticated==false %}
                                disabled placeholder="Login to Chat" {% else %} placeholder="Type Message Here..."
                                {% endif %}>
                            <span class="float-right"><button id="chatSubmit" class="btn btn-success btn-sm"
                                    onclick="sendChat();">Send</button></span>
                        </div>
                    </div>
                </div>
                {% endif %}
            </div>
        </div>
        <div class="tab-pane fade" id="videoList" role="tabpanel" aria-labelledby="videos-tab">
            <div class="row mx-2">
                <div id="recordedVideoList" class="col-lg col-xs-12 col-sm-12">
                    <div class="row">
                        <div class="col-12 col-md-10 col-lg-11"></div>
                        <div class="col-12 col-md-2 col-lg-1">
                            <span class="dropdown">
                                <button class="btn btn-secondary dropdown-toggle shadow" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                    <i class="fas fa-sort"></i> Sort
                                </button>
                                <div class="dropdown-menu shadow" aria-labelledby="dropdownMenuButton">
                                    <span class="sort dropdown-item" data-sort="name">Sort by Name</span>
                                    <span class="sort dropdown-item" data-sort="upvotes">Sort by Upvotes</span>
                                    <span class="sort dropdown-item" data-sort="views">Sort by Views</span>
                                    <span class="sort dropdown-item" data-sort="length">Sort by Length</span>
                                    <span class="sort dropdown-item" data-sort="date">Sort by Date</span>
                                </div>
                            </span>
                        </div>
                    </div>
                    <ul class="itemList list d-flex flex-wrap justify-content-start">
                        {% for video in channel.recordedVideo|sort(attribute='videoDate', reverse=True)%}
                        {% if video.pending == False %}
                        <li class="video-card bg-dark mx-4" style="max-width: 20rem;">
                            <div class="video-card-header">
                                <a href="/play/{{video.id}}">
                                    <img class="shadow {% if video.gifLocation != None %}gif{% endif %} lazy" src="/static/img/video-placeholder.jpg"
                                        width="100%" data-src="/videos/{{video.thumbnailLocation}}"
                                        onerror="this.src='/static/img/video-placeholder.jpg';">
                                </a>
                            </div>
                            <div class="video-card-body">
                                <a href="/play/{{video.id}}"><i class="fas fa-tv mr-2"></i><span class="video-title name"><b>{{video.channelName|limit_title}}</b></span></a><br />
                                {% if video.channel.protected and sysSettings.protectionEnabled %}
                                    <span class="float-right"><span class="badge badge-info"><i class="fas fa-user-lock"></i>Protected</span></span>
                                {% endif %}
                                <br />
                                <i class="fas fa-podcast mr-2"></i><a href="/channel/{{video.channel.id}}/">{{video.channel.channelName}}</a>
                                <span class="float-right date"><i class="fas fa-calendar-alt mr-2"></i>{{video.videoDate|normalize_date}}</span><br />
                                <i class="fas fa-user mr-2"></i><a href="/streamers/{{video.owningUser}}">{{video.owningUser|get_userName}}</a>
                                <span class="float-right"><i class="fas fa-hashtag mr-2"></i><a href="/topic/{{video.topic}}/">{{video.topic|get_topicName}}</a></span><br />
                                <span class="upvotes"><i class="fas fa-thumbs-up mr-2"></i> {{video.id|get_Video_Upvotes}}</span>
                                <span class="views"><i class="fas fa-eye mx-2"></i> {{video.views}}</span>
                                <i class="fas fa-comments mx-2"></i> {{video.id|get_Video_Comments}}
                                <span class="float-right length"><i class="fas fa-clock mr-2"></i>
                                    {{video.length|hms_format}}</span>
                            </div>
                        </li>
                        {% endif %}
                        {% endfor %}
                    </ul>
                </div>
            </div>
        </div>
        <div class="tab-pane fade" id="clipList" role="tabpanel" aria-labelledby="clips-tab">
            <div class="row mx-2">
                <div id="clipsList" class="col-lg-12 col-xs-12 col-sm-12">
                    <div class="row">
                        <div class="col-12 col-md-10 col-lg-11"></div>
                        <div class="col-12 col-md-2 col-lg-1">
                            <span class="dropdown">
                                <button class="btn btn-secondary dropdown-toggle shadow" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                    <i class="fas fa-sort"></i> Sort
                                </button>
                                <div class="dropdown-menu shadow" aria-labelledby="dropdownMenuButton">
                                    <span class="sort dropdown-item" data-sort="name">Sort by Name</span>
                                    <span class="sort dropdown-item" data-sort="upvotes">Sort by Upvotes</span>
                                    <span class="sort dropdown-item" data-sort="views">Sort by Views</span>
                                    <span class="sort dropdown-item" data-sort="length">Sort by Length</span>
                                    <span class="sort dropdown-item" data-sort="date">Sort by Date</span>
                                </div>
                            </span>
                        </div>
                    </div>
                    <ul class="itemList list d-flex flex-wrap justify-content-start">
                        {% for clip in clipsList %}
                        <li class="video-card bg-dark mx-4" style="max-width: 20rem;">
                            <div class="video-card-header">
                                <a href="/clip/{{clip.id}}">
                                    <img class="shadow {% if clip.gifLocation != None %}gif{% endif %} lazy" src="/static/img/video-placeholder.jpg" width="100%" data-src="/videos/{{clip.thumbnailLocation}}" onerror="this.src='/static/img/video-placeholder.jpg';">
                                </a>
                            </div>
                            <div class="video-card-body">
                                <a href="/clip/{{clip.id}}"><i class="fas fa-tv mr-2"></i><span class="video-title name"><b>{{clip.clipName|limit_title}}</b></span></a><br />
                                <span class="float-right"><span class="badge badge-secondary ml-2"><i class="fas fa-user-lock"></i>Clip</span></span>
                                {% if clip.recordedVideo.channel.protected and sysSettings.protectionEnabled %}
                                    <span class="float-right"><span class="badge badge-info"><i class="fas fa-user-lock"></i>Protected</span></span>
                                {% endif %}<br />
                                <i class="fas fa-podcast mr-2"></i><a href="/channel/{{clip.recordedVideo.channel.id}}/">{{clip.recordedVideo.channel.channelName}}</a>
                                <span class="float-right date"><i class="fas fa-calendar-alt mr-2"></i>{{clip.recordedVideo.videoDate|normalize_date}}</span><br />
                                <i class="fas fa-user mr-2"></i><a href="/streamers/{{clip.recordedVideo.owningUser}}">{{clip.recordedVideo.owningUser|get_userName}}</a>
                                <span class="float-right"><i class="fas fa-hashtag mr-2"></i><a href="/topic/{{clip.recordedVideo.topic}}/">{{clip.recordedVideo.channel.topic|get_topicName}}</a></span><br />
                                <span class="upvotes"><i class="fas fa-thumbs-up mr-2"></i> {{clip.id|get_Clip_Upvotes}}</span>
                                <span class="views"><i class="fas fa-eye mx-2"></i> {{clip.views}}</span>
                                <span class="float-right length"><i class="fas fa-clock mr-2"></i>{{clip.length|hms_format}}</span>
                            </div>
                        </li>
                        {% endfor %}
                    </ul>
                </div>
            </div>
        </div>

    </div>
</div>
    {% if channel.owningUser == current_user.id %}
    <!-- Modal -->
    <div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="editModalTitle" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editModalTitle">Edit Stream Info</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <form>
                    <div class="modal-body">
                        <h5>Name of the Stream:</h5>
                        <input type="text" id="editStreamNameInput" class="form-control" value="{{stream.streamName}}" name="newStreamName" required>
                        <br>
                        <h5>Stream Topic:</h5>
                        <select class="form-control" name="newStreamTopic" id="editChannelTopicInput" style="font-family: FontAwesome, sans-serif;" required>
                            {% for topic in topics %}
                            <option value={{topic.id}} {% if stream.topic==topic.id %} selected {% endif %}>{{topic.name}}</option>
                            {% endfor %}
                        </select>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <button type="button" class="btn btn-primary" data-dismiss="modal" onClick="submitStreamChanges()">Save Changes</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    {% endif %}

    <div class="modal fade" id="shareModal" tabindex="-1" role="dialog" aria-labelledby="shareModalTitle" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="shareModalTitle">Share stream</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>

                <div class="modal-body">
                    <div style="margin: 0 auto;width: 99%; text-align: center;">
                        <button type="button" id="FBShareBtn" class="btn" style="background-color:#4267B2;color:white;" onclick="window.open('https://www.facebook.com/sharer/sharer.php?u={{request.url}}','facebook-share-dialog','width=626,height=436');return false;">Share on Facebook</button>
                        <button type="button" id="TwitterShareBtn" class="btn" style="background-color:#1dcaff;color:white;" onclick="window.open('https://twitter.com/share?url={{request.url}}&text=Check out this Stream! - {{stream.streamName}}','twitter-share-dialog','width=626,height=436');return false;">Share on Twitter</button>
                    </div>
                    <br>
                    <div class="form-group row">
                        <label for="embedURLInput" class="col-sm-2 col-form-label"><b>Embed</b></label>
                        <div class="col-sm-10">
                            <div class="input-group mb-3">
                                <div class="input-group-prepend">
                                    <button type="button" class="btn btn-primary" onclick="CopyDiv('embedURLInput')"><i
                                            class="fas fa-copy"></i></button>
                                </div>
                                <input class="form-control" id="embedURLInput" type="text"
                                    value="<iframe src='{{request.url}}?embedded=True' width=600 height=345></iframe>"
                                    readonly onClick="this.select();">
                            </div>
                        </div>
                    </div>
                    <div class="form-group row">
                        <label for="linkShareInput" class="col-sm-2 col-form-label"><b>Link</b></label>
                        <div class="col-sm-10">
                            <div class="input-group mb-3">
                                <div class="input-group-prepend">
                                    <button type="button" class="btn btn-primary" onclick="CopyDiv('linkShareInput')"><i
                                            class="fas fa-copy"></i></button>
                                </div>
                                <input class="form-control" id="linkShareInput" type="text" value="{{request.url}}"
                                    readonly onClick="this.select();">
                            </div>
                        </div>
                    </div>
                    <div class="form-group row">
                        <label for="rtmpURI" class="col-sm-2 col-form-label"><b>RTMP Link</b></label>
                        <div class="col-sm-10">
                            <div class="input-group mb-3">
                                <div class="input-group-prepend">
                                    <button type="button" class="btn btn-primary" onclick="CopyDiv('rtmpURI')"><i
                                            class="fas fa-copy"></i></button>
                                </div>
                                <input class="form-control" id="rtmpURI" type="text" value="{{rtmpURI}}" readonly
                                    onClick="this.select();">
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">

                    <button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>
    {% endblock %}

    {% block scripts %}

    <script>
        var player = videojs('video', {
            autoplay: true,
            errorDisplay: false,
            liveui: true,
            liveTracker: {
                trackingThreshold: 5,
                liveTolerance: 15
            },
            html5:
                {
                    nativeAudioTracks: false,
                    nativeVideoTracks:false,
                    hls:
                        {
                            overrideNative: true
                        }
                },
            plugins : {
                httpSourceSelector: {
                    default: 'auto'
                }
            }
        });

        qualityLevels = player.qualityLevels();
        httpSelector = player.httpSourceSelector();

        player.ready(function () {
            this.src({
                src: '{{streamURL}}',
                type: 'application/x-mpegURL'
            });
        });
        player.play();
    </script>

    <script>
        $(document).ready(function () {
            monitor_vid(player);
        });
    </script>


    <script type="text/javascript" charset="utf-8">
        var conn_options = {
            'sync disconnect on unload': true
        };

        var socket = io("/", {reconnection: true, forceNew: false});
    </script>

    <script>
        socket.on('connect', function () {
            socket.emit('newViewer', { data: '{{channel.channelLoc}}' });
        });
    </script>

    <script>
        socket.on('disconnect', function () {
            socket.emit('removeViewer', { data: '{{channel.channelLoc}}' });
        });
    </script>


    <script>
        window.addEventListener("beforeunload", function (e) {
            socket.emit('removeViewer', { data: '{{channel.channelLoc}}' });
            return null;
        });
    </script>

    <script type="text/javascript" charset="utf-8">
        socket.on('viewerTotalResponse', function (msg) {
            document.getElementById("currentViewers").innerHTML = msg['data'];
            var userBoxHTML = "";
            var userList = msg['userList'];
            var userListLength = userList.length;
            for (var i = 0; i < userListLength; i++) {
                userBoxHTML = userBoxHTML.concat(userList[i], '<br>');
            }
            var userListElement = document.getElementById("userList");
            userListElement.setAttribute("data-content", userBoxHTML);
        });
    </script>

    <script>
        var chatTimer;
        var chatThrottled = false;
        var chatTimeout = 2000;

        function chatThrottleDisable() {
            chatThrottled = false;
        }

        function sendChat() {
            if (chatThrottled == false) {
                text = $('#text').val();
                $('#text').val('');
                socket.emit('text', {msg: text, room: '{{channel.channelLoc}}'});
                chatThrottled = true;
                chatTimer = setTimeout(chatThrottleDisable, chatTimeout);
            }

        };

        $('#text').keypress(function(e) {
            var code = e.keyCode || e.which;
            if (code == 13) {
                sendChat();
            }
        });
    </script>

    <script>

        socket.on('message', function (data) {
            var today = new Date();
            var h = today.getHours();
            var m = (today.getMinutes() < 10 ? '0' : '') + today.getMinutes();
            var s = today.getSeconds();
            //var message = decodeURIComponent((escape(decodeURIComponent(data['msg']))));
            var message = data['msg'];
            if (data['flags'] === 'Owner') {
                $('#chat').append('<div class="chatBar-Item chat-{{channel.chatBG}} {{channel.chatAnimation}}"><div class="charBar-Item-Image"><img src="' + data['image'] + '" width="52px" height="52px"></div><div class="chatBar-Item-Text" style="color:{{channel.chatTextColor}};"><b>' + data['user'] + '</b> <i class="fas fa-crown"></i> ' + h + ':' + m + '<br>' + message + '</div></div>');
            } else if (data['flags'] === 'Bot') {
                $('#chat').append('<div class="chatBar-Item chat-{{channel.chatBG}} {{channel.chatAnimation}}"><div class="charBar-Item-Image"><img src="' + data['image'] + '" width="52px" height="52px"></div><div class="chatBar-Item-Text" style="color:{{channel.chatTextColor}};"><b>' + data['user'] + '</b> <i class="fas fa-robot"></i> ' + h + ':' + m + '<br>' + message + '</div></div>');
            } else {
                $('#chat').append('<div class="chatBar-Item chat-{{channel.chatBG}} {{channel.chatAnimation}}"><div class="charBar-Item-Image"><img src="' + data['image'] + '" width="52px" height="52px"></div><div class="chatBar-Item-Text" style="color:{{channel.chatTextColor}};"><b>' + data['user'] + '</b> ' + h + ':' + m + '<br>' + message + '</div></div>');
            }
            $('#chat').animate({ scrollTop: 1000000 }, "fast");
        });
    </script>

    <script>
        $(function () {
            $('[data-toggle="popover"]').popover()
        })
        $('.popover-dismiss').popover({
            trigger: 'focus'
        })
    </script>

    <script>
        setInterval(function () {
            socket.emit('getViewerTotal', { data: "{{channel.channelLoc}}" });
        }, 5000);
    </script>

    <script>
        socket.on('connect', function () {
            socket.emit('getUpvoteTotal', { loc: '{{channel.channelLoc}}', vidType: 'stream' });
        });
    </script>

    <script>
        setInterval(function () {
            socket.emit('getUpvoteTotal', { loc: '{{channel.channelLoc}}', vidType: 'stream' });
        }, 30000);
    </script>

<script type="text/javascript" charset="utf-8">
    socket.on('upvoteTotalResponse', function (msg) {
        document.getElementById("totalUpvotes").innerHTML = msg['totalUpvotes'];
        if (msg['myUpvote'] === 'True'){
            if ( document.getElementById("upVoteIcon").classList.contains('far') ) {
                document.getElementById("upVoteIcon").classList.remove('far');
                document.getElementById("upVoteIcon").classList.add('fas');
            }
        }
        else if (msg['myUpvote'] === 'False'){
            if ( document.getElementById("upVoteIcon").classList.contains('fas') ) {
                document.getElementById("upVoteIcon").classList.remove('fas');
                document.getElementById("upVoteIcon").classList.add('far');
            }
        }
    });
</script>

    <script>
        function changeUpvote() {
            socket.emit('changeUpvote', { loc: '{{channel.channelLoc}}', vidType: 'stream' });
        }
    </script>

    <script>
        function toggleChat() {
            var chatbox = document.getElementById("chatside");
            if (chatbox.style.display === "none") {
                chatbox.style.display = "block";
            } else {
                chatbox.style.display = "none";
            }
        }
    </script>

    <script>
        function popoutChat() {
            MyWindows = window.open('/view/{{channel.channelLoc}}/?chatOnly=True', 'myWindow', 'width=500,height=850');
            var chatbox = document.getElementById("chatside");
            chatbox.style.display = "none";
        }
    </script>

    <script>
        function submitStreamChanges() {
            var newStreamNameDiv = document.getElementById("editStreamNameInput");
            var newStreamTopicDiv = document.getElementById("editChannelTopicInput");

            socket.emit('updateStreamData', { name: newStreamNameDiv.value, topic: newStreamTopicDiv.value, channel: "{{channel.channelLoc}}" });
        }
    </script>


    <script>
        //Fixes for VideoJS on Disconnect to Force a Reconnect when the readyState is stuck at 2
        function monitor_vid(vidplayer) {


            videoJSObj = vidplayer;
            currentReadyState = videoJSObj.readyState();

            videoWindowState = document.getElementsByTagName('video');

            videoContainer = document.getElementById('videoContainer');
            offlineWindow = document.getElementById('offlineImage');

            onlineBadge = document.getElementById('liveIndicatorBadge');

            $.getJSON('/apiv1/channels/{{channel.channelLoc}}', function (data) {
                var channelList = data['results'][0];
                var streamIDList = channelList['stream'];

                if (streamIDList.length > 0) {
                    var currentStreamID = streamIDList[0];

                    videoContainer.style.display = "block";
                    offlineWindow.style.display = "none";

                    if (currentReadyState <= 2) {
                        try {
                            videoJSObj.reset();
                            videoJSObj.src('{{streamURL}}');
                            videoJSObj.pause().trigger('loadstart');
                            videoJSObj.play();
                        } catch (e) {
                            console.log("OSP tried restarting the stream but had an issue:" + e)
                        }
                    }


                    $.getJSON('/apiv1/streams/' + currentStreamID, function (data) {
                        var streamData = data['results'][0];
                        var currentStreamTopic = streamData['topic'];
                        var currentStreamName = streamData['streamName'];

                        var topicDiv = document.getElementById('streamMetadataTopic');
                        var nameDiv = document.getElementById('streamMetadataName');

                        var topicJSList = [];
                        {% for x in topics %}
                        topicJSList["{{x.id}}"] = "{{x.name}}";
                        {% endfor %}


                        var nameDivHTML = '<b><i class="fas fa-video"></i> <span> ' + currentStreamName + '</span></b>';
                        var topicDivHTML = '<b><i class="fas fa-hashtag"></i> <a href="/topics/' + currentStreamTopic + '"><span>' + topicJSList[currentStreamTopic] + '</span></a></b>';

                        onlineBadge.className = 'float-left m-2 liveindicator badge badge-danger';
                        onlineBadge.innerHTML = '<i class="fas fa-video"></i><span class="d-none d-sm-none d-md-inline"> Live</span>';

                        nameDiv.innerHTML = nameDivHTML;
                        topicDiv.innerHTML = topicDivHTML;

                    });

                } else {
                    try {
                        videoJSObj.pause();
                        videoJSObj.reset();
                        onlineBadge.className = 'float-left m-2 liveindicator badge badge-secondary';
                        onlineBadge.innerHTML = '<i class="fas fa-video-slash"></i><span class="d-none d-sm-none d-md-inline"> Offline</span>';
                        videoContainer.style.display = "none";
                        offlineWindow.style.display = "block";
                        var currentStreamName = "No Stream";
                        var nameDiv = document.getElementById('streamMetadataName');
                        var nameDivHTML = '<span><b> ' + currentStreamName + '</b></span>';
                        nameDiv.innerHTML = nameDivHTML;

                    } catch (e) {
                        console.log("OSP tried restarting the stream but had an issue:" + e)
                    }
                }
            });
            var lastVideoState = currentReadyState;
        }

        setInterval(function () {
            monitor_vid(player);
        }, 10000);
    </script>

    <script>
        function CopyDiv(divVal) {
            var copyText = document.getElementById(divVal);
            copyText.select();
            document.execCommand("copy");
        }
    </script>

    <script>
        function toggleChannelSub(chanID) {
            socket.emit('toggleChannelSubscription', { channelID: chanID });
        }
    </script>
    <script>

        socket.on('sendChanSubResults', function (msg) {
            var subButton = document.getElementById('chanSubStateButton');
            if (msg['state'] === true) {
                subButton.innerHTML = "<i class='fas fa-star'></i>";
                subButton.className = "btn btn-outline-success";
            } else {
                subButton.innerHTML = "<i class='far fa-star'></i>";
                subButton.className = "btn btn-outline-secondary";
            }
        });
    </script>

    <script>
        videoListOptions = {
            valueNames: ['name', 'upvotes', "views", "length", "date"]
        };

        clipListOptions = {
            valueNames: ['name', 'upvotes', "views", "length", "date"]
        };

        var recordedVideosList = new List('recordedVideoList', videoListOptions);
        var clipList = new List('clipsList', clipListOptions);

    </script>

    <script>
      const video = document.querySelector('video');
      video.addEventListener('play', (event) => {
        var cookieVolume = getCookie('ospvolume');
        if (!(cookieVolume == null)) {
          player.volume(cookieVolume);
        }
      });

      video.addEventListener('volumechange', (event) => {
        var currentVolume = player.volume();
        setCookie('ospvolume',currentVolume, 365);
      });
    </script>

    {% endblock %}